package cn.levi.path.config;


import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.levi.path.annotation.FilePathAuto;
import cn.levi.path.component.URLPathHandler;
import cn.levi.path.configuration.UrlProperties;
import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import java.io.IOException;
import java.util.Objects;

/**
 * 文件路径反序列化时去掉前缀和鉴权参数
 *
 * @author lei
 * @since 2024/9/13
 */
public class FilePathDeserialize extends JsonDeserializer<String> implements ContextualDeserializer {

	private FilePathAuto filePathAuto;

	public FilePathDeserialize( ) {}
	public FilePathDeserialize(FilePathAuto filePathAuto) {
		this.filePathAuto = filePathAuto;
	}

	@Override
	public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JacksonException {
		UrlProperties urlProperties = SpringUtil.getBean(UrlProperties.class);
		String text = p.getText();
		if (!urlProperties.isEnable()) {
			return text;
		}
		if (StrUtil.isBlank(text)) {
			return text;
		}
		URLPathHandler urlPathHandler = SpringUtil.getBean(URLPathHandler.class);
		return urlPathHandler.getPath(text);
	}


	@Override
	public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException {
		if (!Objects.equals(property.getType().getRawClass(), String.class)) {
			return ctxt.findContextualValueDeserializer(property.getType(),property);
		}
		FilePathAuto filePathAutoTarget = property.getAnnotation(FilePathAuto.class);
		if (filePathAutoTarget == null) {
			return ctxt.findContextualValueDeserializer(property.getType(),property);
		}
		return new FilePathDeserialize(filePathAutoTarget);
	}
}
